package com.th.contraller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.th.dao.*;
import com.th.entity.Obj;
import com.th.entity.User;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import  java.util.*;
import java.text.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.time.LocalDate;
import java.util.List;

@WebServlet(name="UserMag",urlPatterns = {"/selectObjsByType","/upImg","/applyUpObj", "/modifyUser", "/applyGetObj", "/updateObjs", "/selectObjsByKeys", "/seeMyUps", "/seeMyGets", "/seeMyUpHis", "/seeMyGetHis"})
@MultipartConfig
@Component

public class UserMag extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        try {
            Method method = UserMag.class.getDeclaredMethod(uri.substring(uri.lastIndexOf("/")+1,uri.length()),HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        try {
            Method method = UserMag.class.getDeclaredMethod(uri.substring(uri.lastIndexOf("/")+1,uri.length()),HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //图片上传
    public void upImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        String get_id = request.getParameter("get_id");
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = (ObjDaoImp)context.getBean("objDaoImp",ObjDaoImp.class);
        Obj obj = objDaoImp.selectObjById(Integer.parseInt(get_id));
        Part part = request.getPart("img");
        String header = part.getHeader("content-disposition");
        String filePath = getServletContext().getRealPath("/images")+"/"+ header.substring(header.lastIndexOf("=")+2, header.lastIndexOf("\""));
        part.write(filePath);

        String imgPath = "https://www.shanhe.love/lost_get/images/"+header.substring(header.lastIndexOf("=")+2, header.lastIndexOf("\""));
        obj.setImg(imgPath);
        objDaoImp.updateObj(obj);
        out.write(mapper.writeValueAsString(imgPath));
    }
    //编码更新
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateCode()
    {
        Date date = Date.valueOf(LocalDate.now());
        String year = String.valueOf(date.getYear()).substring(1,3);
        String month = String.valueOf(date.getMonth()+1);
        if(month.length() == 1)
        {
            month = "0"+month;
        }
        String day = String.valueOf(date.getDate());
        if(day.length() == 1)
        {
            day = "0"+day;
        }
        getServletContext().setAttribute("get_id",Integer.parseInt(year +month +day)*100);
    }
    //用户上传
    public void applyUpObj(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        Obj obj = new Obj();
        ServletContext servletContext = getServletContext();
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        obj.setGet_name(request.getParameter("objName"));
        obj.setGet_detail(request.getParameter("objDetail"));
        obj.setGet_add(request.getParameter("objAdd"));
        obj.setObj_type(request.getParameter("objType"));
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        obj.setGet_date(ft.parse(request.getParameter("objDate")));
        obj.setGet_num(user.getOpenid());
        obj.setGet_states(0);
        int id = (Integer)servletContext.getAttribute("get_id");
        servletContext.setAttribute("get_id",id+1);
        obj.setGet_id(id);
        objDaoImp.applyUpObj(obj);
        out.write(mapper.writeValueAsString(obj));
    }

    //完善用户信息
    public void modifyUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        User user = (User)request.getSession().getAttribute("user");
        user.setName(request.getParameter("userName"));
        user.setSex(request.getParameter("userSex"));
        user.setAge(Integer.parseInt(request.getParameter("userAge")));
        user.setGrade(Integer.parseInt(request.getParameter("userGrade")));
        user.setMajor(request.getParameter("userMajor"));
        user.setPhone(request.getParameter("userPhone"));
        user.setCollege(request.getParameter("userCollege"));
        user.setStuNum(request.getParameter("userStuNum"));
        user.setAddress(request.getParameter("userAddress"));
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        UserDao userDao = context.getBean("userDaoImp",UserDao.class);
        userDao.updateUser(user);
        user = userDao.selectUser(user.getOpenid());
        request.getSession().setAttribute("user",user);
        out.print(mapper.writeValueAsString(user));
    }

    //申请领取
    public void applyGetObj (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        User user = (User)request.getSession().getAttribute("user");
        int get_id = Integer.parseInt(request.getParameter("get_id"));
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        objDaoImp.applyGetObj(get_id,user.getOpenid());
    }

    //首页跟新
    public void updateObjs (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        List<Obj> list = objDaoImp.selectObjs(Integer.parseInt(request.getParameter("page")),10,1);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        PrintWriter out = response.getWriter();
        out.print(mapper.writeValueAsString(list));
    }

    //模糊查询
    public void selectObjsByKeys(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        List<Obj> list = objDaoImp.selectObjsByKeys(Integer.parseInt(request.getParameter("page")),10,request.getParameter("keys"));
        mapper.writeValueAsString(list);
        out.print(mapper.writeValueAsString(list));
    }

    //查看我的上传申请
    public void seeMyUps (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        User user = (User)request.getSession().getAttribute("user");
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        List<Obj> list = objDaoImp.selectMyUps(user.getOpenid());
        out.write(mapper.writeValueAsString(list));
    }
    //查看我的领取
    public void seeMyGets (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        User user = (User)request.getSession().getAttribute("user");
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        List<Obj> list = objDaoImp.selectMyGets(user.getOpenid());
        out.write(mapper.writeValueAsString(list));
    }

    //查看我的上传历史
    public void seeMyUpHis (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        User user = (User)request.getSession().getAttribute("user");
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        HistoryDao historyDaoImp = context.getBean("historyDaoImp", HistoryDao.class);
        List<Obj> list = historyDaoImp.selectHistoryByLostNum(user.getOpenid());
        out.write(mapper.writeValueAsString(list));
    }

    //查看我的领取历史
    public void seeMyGetHis (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        if(request.getSession().getAttribute("user") == null)
        {
            String error = "用户未登录,请登录后操作";
            out.print(mapper.writeValueAsString(error));
            return;
        }
        User user = (User)request.getSession().getAttribute("user");
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        HistoryDao historyDaoImp = context.getBean("historyDaoImp", HistoryDao.class);
        List<Obj> list = historyDaoImp.selectHistoryByGetNum(user.getOpenid());
        out.write(mapper.writeValueAsString(list));
    }

    //分类查询
    public void selectObjsByType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        ApplicationContext context = new ClassPathXmlApplicationContext("dao.xml");
        ObjDaoImp objDaoImp = context.getBean("objDaoImp",ObjDaoImp.class);
        List<Obj> list = objDaoImp.selectObjsByType(Integer.parseInt(request.getParameter("page")),10,request.getParameter("type"));
        mapper.writeValueAsString(list);
        out.print(mapper.writeValueAsString(list));
    }
}
